﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using RingSong.Function;
using System.Collections.ObjectModel;
using RingSong.ViewModels;
using Microsoft.Phone.BackgroundTransfer;
using System.IO.IsolatedStorage;
using Microsoft.Phone;
using System.IO;
using Microsoft.Phone.Tasks;

namespace RingSong
{
    public partial class MainPage : MyPage
    {
        public static ListBox lst = null;
        public static Panorama panorama = null;
        public static TextBlock SearchFail = null;
        public static TextBlock TypeFail = null;
        public static TextBox Txt = null;
        SaveRingtoneTask saveRing;
        string typeid = null;
        static string _txt = "";//临时文本框内容
        // 构造函数
        public MainPage()
        {
            InitializeComponent();
            lst = list4;
            SearchFail = searchFail;
            panorama = pan;
            Txt = txt;
            TypeFail = typeFail;
            // 将 listbox 控件的数据上下文设置为示例数据
            LayoutRoot.DataContext = App.ViewModel;
            if (BackgroundTransferService.Requests.Count() != 0)
            {
                foreach (BackgroundTransferRequest b in BackgroundTransferService.Requests)
                    BackgroundTransferService.Remove(b);
            }
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            list1.LayoutUpdated += new EventHandler(list1_LayoutUpdated);
            list2.LayoutUpdated += new EventHandler(list2_LayoutUpdated);
            list3.LayoutUpdated += new EventHandler(list3_LayoutUpdated);
            list5.LayoutUpdated += new EventHandler(list5_LayoutUpdated);

            Dictionary<string, RingViewModel> dict = Com.GetSetting("down") as Dictionary<string, RingViewModel>;
            if (dict != null && dict.Count != 0)
            {
                var result = from pair in dict orderby pair.Key descending select pair;
                Dictionary<string, RingViewModel> dict2 = dict.ToDictionary(p => p.Key, p => p.Value);
                int bs = 1;
                foreach (string key in dict2.Keys)
                {
                    dict2[key].Tag = bs.ToString();
                    App.ViewModel.Items4.Insert(0, dict2[key]);
                    bs++;
                }
            }
            App.ViewModel.IsDataLoaded[3] = true;
            Com.CheckPath();
            media.Volume = 100;
            media.MediaEnded += new RoutedEventHandler(media_MediaEnded);
            saveRing = new SaveRingtoneTask();
            saveRing.Completed += new EventHandler<TaskEventArgs>(saveRing_Completed);
        }

        // 为 ViewModel 项加载数据
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded[0]) App.ViewModel.LoadData();
            foreach (RingViewModel r in App.ViewModel.Items4)
            {
                if (r.Progress != 100)
                {
                    Anm.Show_Hide(r, "wait", true, list4);
                    Down.lst.Add(r); //加入下载队列，但不立即下载。
                }
            }
        }

        void list2_LayoutUpdated(object sender, EventArgs e)
        {
            string _url = UrlMark.MarkUrl(UrlMark.url_getlst) + "flag=0&typeid=0";
            _list_LayoutUpdated(list1, App.ViewModel.Isnextpage[0], App.ViewModel.P[0], App.ViewModel.Pagesize[0], 1, _url);
        }

        void list1_LayoutUpdated(object sender, EventArgs e)
        {
            string _url = UrlMark.MarkUrl(UrlMark.url_getlst) + "flag=1&typeid=0";
            _list_LayoutUpdated(list2, App.ViewModel.Isnextpage[1], App.ViewModel.P[1], App.ViewModel.Pagesize[1], 2, _url);
        }

        void list3_LayoutUpdated(object sender, EventArgs e)
        {
            string _url = UrlMark.MarkUrl(UrlMark.url_getlst) + "flag=1&typeid=0"
                                + "&key=" + txt.Text.Trim();
            _list_LayoutUpdated(list3, App.ViewModel.Isnextpage[2], App.ViewModel.P[2], App.ViewModel.Pagesize[2], 3, _url);
        }

        void list5_LayoutUpdated(object sender, EventArgs e)
        {
            string _url = UrlMark.MarkUrl(UrlMark.url_getlst) + "flag=1&typeid=0" + typeid;
            _list_LayoutUpdated(list5, App.ViewModel.Isnextpage[4], App.ViewModel.P[4], App.ViewModel.Pagesize[4], 5, _url);
        }

        void _list_LayoutUpdated(ListBox listbox, int isnextpage, int p, int pagesize, int f, string _url)
        {
            ScrollViewer scrollViewer = Com.FindChildOfType<ScrollViewer>(listbox);
            if (scrollViewer != null)
            {
                if (isnextpage == 1 && !MyPage._progress.IsVisible &&
                    scrollViewer.VerticalOffset + 5 >= scrollViewer.ScrollableHeight &&
                    listbox.Items.Count > 0)
                {
                    App.ViewModel.P[f - 1]++;
                    _url += "&p=" + App.ViewModel.P[f - 1];
                    App.ViewModel.GetData(_url, f);
                }
            }
        }

        private void Panorama_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //初始化工作
            if (pan.SelectedIndex == 1 && !App.ViewModel.IsDataLoaded[1])//最新
            {
                string _url = UrlMark.MarkUrl(UrlMark.url_getlst)
                    + "&p=" + App.ViewModel.P[1]
                    + "&flag=0&typeid=0";
                App.ViewModel.GetData(_url, 2);
            }
            else if (pan.SelectedIndex == 3) //下载历史
            {
                if (!App.ViewModel.IsDataLoaded[3])
                {
                    Dictionary<string, RingViewModel> dict = Com.GetSetting("down") as Dictionary<string, RingViewModel>;
                    if (dict == null || dict.Count == 0)
                    {
                        App.ViewModel.IsDataLoaded[3] = true; return;
                    }
                    int b = 1;
                    foreach (string key in dict.Keys)
                    {
                        dict[key].Tag = b.ToString();
                        App.ViewModel.Items4.Insert(0, dict[key]);
                        b++;
                    }
                }
                App.ViewModel.IsDataLoaded[3] = true;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (txt.Text == "" || txt.Text == _txt) return;
            if (App.ViewModel.Items3.Count > 0) App.ViewModel.Items3.Clear();
            _txt = txt.Text;
            searchFail.Visibility = Visibility.Collapsed;
            string _url = UrlMark.MarkUrl(UrlMark.url_getlst)
                + "&p=" + App.ViewModel.P[2]
                + "&key=" + HttpUtility.UrlEncode(txt.Text.Trim()) + "&flag=1&typeid=0"; ;
            App.ViewModel.GetData(_url, 3);
        }

        private void list1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RingViewModel r = (sender as ListBox).SelectedItem as RingViewModel;
            if (r == null) return;
            if (Down.lst.Count >= 5) { MessageBox.Show("已经有5个在下载了，先等待下载完吧！"); return; }
            if (list4.Items.Count > 200) { MessageBox.Show("你已经下载了200个铃声，这么多铃声用不上！删掉点再下新的吧！"); return; }
            Dictionary<string, RingViewModel> dict = Com.GetSetting("down") as Dictionary<string, RingViewModel>;
            if (dict == null) dict = new Dictionary<string, RingViewModel>();

            if (!dict.ContainsKey(r.Infoid) || Down.lst.Contains(r))
            {
                if (App.ViewModel.IsDataLoaded[3])  //如果初始化过了，就添加到界面上
                {
                    int b = App.ViewModel.Items4.Count + 1;
                    r.Tag = b.ToString();
                    App.ViewModel.Items4.Insert(0, r);
                    list4.UpdateLayout();
                    if (Down.CountDown() < 5)
                        Anm.Show_Hide(App.ViewModel.Items4[0], "wait", true, list4);
                    else
                        Anm.Show_Hide(App.ViewModel.Items4[0], "pro", true, list4);
                }
                dict[r.Infoid] = r;
                Down.lst.Add(new RingViewModel());
                Down.lst[Down.lst.Count - 1] =
                    (App.ViewModel.IsDataLoaded[3] && App.ViewModel.Items4.Count > 0) ? App.ViewModel.Items4[0] : r;
                Down.Download();
                Com.SetSetting("down", dict);
                Com.Msg("已经加入到下载历史中《" + r.Title + "》...");
            }
            else
            {
                Com.WarnMsg("已经下载过(点击查看)" + r.Title + "！", r); return;
            }
        }

        private void list4_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (list4.SelectedItem == null) return;
            RingViewModel r = list4.SelectedItem as RingViewModel;

            if ((list4.SelectedItem as RingViewModel).Progress != 100) return;

            if (Anm.isShowBtns.Contains(r))  //如果按的是已经打开的
            {
                Anm.Show_Hide(r, "btns", false, list4);
                return;
            }

            foreach (RingViewModel _r in Anm.isShowBtns)
                Anm.Show_Hide(_r, "btns", false, list4);
            
            //关闭已经打开的所有按钮
            if (Anm.isShowBtns.Contains(r) || Anm.isShowPro.Contains(r) || Anm.isShowWait.Contains(r))  //关闭已经打开的自己
                Anm.CloseOne(r, list4);
            if (!Anm.CheckBtns(list4.SelectedItem, list4))
            {
                list4.SelectedIndex = -1;
                return;
            }
            Anm.Show_Hide(list4.SelectedItem, "btns", true, list4);
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem item = sender as MenuItem;
            var r = ((MenuItem)sender).Tag as RingViewModel;
            if (r == null) return;

            if (item.Header.ToString() == "重新下载" || item.Header.ToString() == "下载")
            {
                if (!Down.lst.Contains(r)) Down.lst.Add(r);
                Down.Download();
                Anm.Show_Hide(r, "wait", true, list4);
                Com.Msg("正在重新下载《" + r.Title + "》");
            }
            else if (item.Header.ToString() == "删除")
            {
                Del(r);
                if (Down.lst.Contains(r)) Down.lst.Remove(r);
            }
        }
        //按钮 播放
        private void Btn_Play(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            if (btn.Content.ToString() == "播放")
            {
                var r = Com.getRingContent(btn);
                IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                string filepath = "shared\\transfers\\" + r.Infoid + ".mp3";
                if (!myIsolatedStorage.FileExists(filepath))
                {
                    MessageBox.Show("文件不存在，请尝试重新下载！"); return;
                }
                if (media.Tag != null)  //关闭已经打开的
                {
                    Com.SetBtnContent(media.Tag);
                    media.Tag = null;
                }
                media.Tag = r;
                Com.playSong(media, filepath);
                btn.Content = "停止";
            }
            else
            {
                if (media.CurrentState == MediaElementState.Playing) media.Stop();
                btn.Content = "播放";
                media.Source = null;
                media.Tag = null;
            }
            return;
        }
        //播放完毕时
        void media_MediaEnded(object sender, RoutedEventArgs e)
        {
            //先判断是否展开
            if (Anm.isShowBtns.Contains(list4.SelectedItem))
            {
                Com.SetBtnContent(list4.SelectedItem);  //找出选中项并设置按钮内容
                media.Tag = null;
            }
        }
        //按钮 删除
        private void Btn_Del(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("确定删除吗?", "删除询问", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                return;
            var r = Com.getRingContent(sender as Button);
            //删设置
            Del(r);
        }
        //按钮 设置为铃声
        private void Btn_Set(object sender, RoutedEventArgs e)
        {
            var r = Com.getRingContent(sender as Button);
            string path = "isostore:/shared/transfers/" + r.Infoid + ".mp3";
            try
            {
                saveRing.Source = new Uri(path);
                saveRing.DisplayName = r.Title;
                _progress.IsVisible = true;
                saveRing.Show();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }

        }
        //铃声设置回调
        void saveRing_Completed(object sender, TaskEventArgs e)
        {
            if (e.TaskResult == TaskResult.OK)
                Com.SuccMsg("成功保存铃声！");
            else
                Com.SuccMsg("铃声保存失败！");
            _progress.IsVisible = false;
        }

        //绘制MenuContent
        private void list_Hold(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        {
            StackPanel pan = sender as StackPanel;
            Grid grd = Com.GetChildObject<Grid>(pan, "grd");
            Grid pro = Com.GetChildObject<Grid>(grd, "pro");
            ProgressBar bar = Com.GetChildObject<ProgressBar>(pro, "proBar");
            ContextMenu contextMenu = ContextMenuService.GetContextMenu(pan);
            MenuItem item1 = contextMenu.Items[0] as MenuItem;
            MenuItem item2 = contextMenu.Items[1] as MenuItem;
            item1.Visibility = Visibility.Visible;
            item2.Visibility = Visibility.Visible;
            item1.Header = "重新下载";
            item2.Header = "删除";
            if (bar.Value >= 100) //下载已经完成
                item2.Visibility = Visibility.Collapsed; //隐藏删除
            else //没有下载完成
            {
                if (Down.lst.Count != 0 && !Down.isLoadingDown)
                    item1.Header = "下载";
                else
                    item1.Visibility = Visibility.Collapsed;
            }
        }

        //删除函数
        public void Del(RingViewModel r)
        {
            //删设置
            Dictionary<string, RingViewModel> dict = Com.GetSetting("down") as Dictionary<string, RingViewModel>;
            dict.Remove(r.Infoid);
            Com.SetSetting("down", dict);
            //删文件 删除前先判断是否在播放
            string filepath = "shared/transfers/" + r.Infoid + ".mp3";
            if (media.Source != null && media.Tag == r)
            {
                if (media.CurrentState == MediaElementState.Playing) media.Stop();
                media.Source = null;
            }
            IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
            if (myIsolatedStorage.FileExists(filepath))
                myIsolatedStorage.DeleteFile(filepath);
            //删项
            App.ViewModel.Items4.Remove(r);
            //删除动画存档
            if (Anm.isShowWait.Contains(r)) Anm.isShowWait.Remove(r);
            if (Anm.isShowPro.Contains(r)) Anm.isShowPro.Remove(r);
            if (Anm.isShowBtns.Contains(r)) Anm.isShowBtns.Remove(r);
            //更新序号
            int b = 0;
            for (int i = App.ViewModel.Items4.Count - 1; i >= 0; i--)
            {
                b++;
                App.ViewModel.Items4[i].Tag = b.ToString();
            }
        }

        //分类方块按钮
        private void BtnType_Click(object sender, RoutedEventArgs e)
        {
            Storyboard1.Completed += (_, __) =>
            {
                listBox.Visibility = Visibility.Collapsed;
                list5.Visibility = Visibility.Visible;
            };
            _progress.IsVisible = true;
            Storyboard1.Begin();
            Button btn = sender as Button;
            App.ViewModel.P[4] = 1;
            string _url = UrlMark.url_getlst + "flag=0&typeid=" + btn.CommandParameter
                        + "&p=" + App.ViewModel.P[4];
            App.ViewModel.GetData(_url, 5);
            pan5.Header = btn.Content;
        }

        //分类返回按钮
        private void BtnBack_Click(object sender, RoutedEventArgs e)
        {
            backType();
        }
        //分类返回函数
        void backType()
        {
            list5.Visibility = Visibility.Collapsed;
            listBox.Opacity = 1;
            listBox.Visibility = Visibility.Visible;
            App.ViewModel.Items5.Clear();
            typeFail.Visibility = Visibility.Collapsed;
            pan5.Header = "分类";
            Storyboard2.Begin();
        }
        //回退事件
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (pan.SelectedIndex == 4 && listBox.Visibility == Visibility.Collapsed)
            {
                backType();
                e.Cancel = true;
            }
            else if (pan.SelectedIndex == 3 && Anm.isShowBtns.Count != 0)
            {
                foreach (object o in Anm.isShowBtns)
                    Anm.Show_Hide(o, "btns", false, list4);
                e.Cancel = true;
            }

            base.OnBackKeyPress(e);
        }

        private void HyperlinkButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            new WebBrowserTask() { Uri = new Uri("http://www.wpgo.cn", UriKind.Absolute) }.Show();
        }

    }

}